package com.yulan.fastkillcourse.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yulan.fastkillcourse.Dto.CourseDto;
import com.yulan.fastkillcourse.common.exception.ControllerException;
import com.yulan.fastkillcourse.model.*;
import com.yulan.fastkillcourse.result.CodeMsg;
import com.yulan.fastkillcourse.result.Result;
import com.yulan.fastkillcourse.service.*;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;


import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 课程中心
 *
 */
@RestController
@RequestMapping("course")
@Validated
public class CourseController implements InitializingBean {

    @Autowired
    CourseService courseService;

    @Autowired
    CourseMarginService courseMarginService;

    @Autowired
    CourseTrackService courseTrackService;

    @Autowired
    CourseDiscussService courseDiscussService;

    @Autowired
    CourseOrderService courseOrderService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;


    @Autowired
    ModelMapper modelMapper;


    private ZSetOperations<String, String> vo ;

    @Override
    public void afterPropertiesSet() throws Exception {
        vo = redisTemplate.opsForZSet();
        for(CourseMargin courseMargin : courseMarginService.list()){
            vo.add("courseRank",  "" +courseMargin.getCid(),(double)courseMargin.getHot());
        }

        System.out.println(vo.reverseRange("courseRank",0,10));
    }

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        //只要网页中传来的数据格式为yyyy-MM-dd 就会转化为Date类型
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
                                true));
    }
    /**
     * 新增课程接口
     */
    @PostMapping("/saveOrUpdate")
    public Result<Integer> saveOrUpdate(CourseDto courseDto){

        System.out.println(courseDto);
        //插入课程表
        Course course =modelMapper.map(courseDto,Course.class);
        courseService.saveOrUpdate(course);

        //插入课程余量、热度、评分
        CourseMargin courseMargin = modelMapper.map(courseDto,CourseMargin.class);
        courseMarginService.saveOrUpdate(courseMargin);

        return Result.success(1);
    }

    /**
     * 管理员修改课程状态
     *
     */
    @PostMapping("/change")
    public Result<Integer> changeCourseStatus(@RequestBody CourseTrack courseTrack){

        if(courseTrack.getStatus()>2 || courseTrack.getStatus()<-1) return Result.error(CodeMsg.REQUEST_ILLEGAL);

        courseTrackService.saveOrUpdate(courseTrack);

        return Result.success(1);
    }

    /**
     *
     * 获取课程排名
     */
    @GetMapping("/top")
    public Result<List<Course>> getTop(@RequestParam Integer l,@RequestParam Integer r){

        Set<String> courseIdSet = vo.reverseRange("courseRank",l,r);
        ArrayList<Course> courses = new ArrayList<>();
        if(courseIdSet == null){
            return  Result.error(CodeMsg.HAVENT_ANY_COURSES);
        }
        System.out.println(courseIdSet);
        for(String str:courseIdSet){
            courses.add(courseService.getById(Integer.parseInt(str)));
        }

        return new Result<>(courses);
    }



    @GetMapping("/list")
    public Result<List<CourseDto>> getAllCourse(@RequestParam(value = "cid",required = false) Integer cid){
        if(cid == null){
            List<CourseDto>  courseDtoList = courseService.getAll();
            return new Result<>(courseDtoList);
        }
        List<CourseDto>  courseDtoList = new ArrayList<>();
        courseDtoList.add(courseService.getOne(cid));
        return new Result<>(courseDtoList);
    }


    /**
     * 获取课程的评论信息
     */
    @GetMapping("/getDiscuss")
    public Result<List<CourseDiscuss>> getCourseDiscuss(@RequestParam Integer cid){
        if(cid == null) {
            return  Result.error(CodeMsg.PARAM_EXCEPTION);
        }

        QueryWrapper<CourseDiscuss> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cid",cid);

        List<CourseDiscuss> list = courseDiscussService.list(queryWrapper);

        if(list == null) {
            throw new ControllerException("此课程暂时没有评论");
        }

        return new Result<>(list);
    }

    /**
     *删除课程全部信息
     */
    @DeleteMapping("/delete")
    public Result<Integer> deleteCourse( @RequestParam(required = false) Integer cid){
        Course course = courseService.getById(cid);
        if(course == null) return Result.error(CodeMsg.HAVENT_ANY_COURSES);
        boolean success1 = courseService.removeById(cid);
        boolean success2 = courseMarginService.removeById(cid);
        boolean success3 = courseDiscussService.removeById(cid);
        if(!success1||!success2||!success3) return Result.error(CodeMsg.SERVER_ERROR);

        return Result.success(1);
    }












}
